<template>
	<!-- <view class="main-class"> -->
	<z-paging ref="paging" v-model="goodsData" @query="queryList" >
		<template #top>
		<tn-sticky> 
			<view class="header-class tn-flex justify-end" >
				<view class="status_bar" style="height: var(--status-bar-height); width: 100%; "></view>
				
				<tn-navbar height="45px"  home-icon="left" back-icon="" :bottom-shadow = "false" bg-color="tn-type-primary_bg" text-color="tn-white"
					index-url="/pages/purplan/purplan"
				>
					采购计划
				</tn-navbar>
					
				<view class="tn-ml-sm tn-text-bold tn-text-lg tn-gray-light_text tn-flex " @click="selSupp">
					<span>{{hz.businessname}}</span>
					<tn-icon name="down-triangle" size="40" />
				</view>
				
				<tn-search-box
					v-model="searchValue"
					@input="searchInputEvent"
					@search="searchBtnClickEventPage"
					size="sm"
					placeholder="搜索关键词,检索品种"
					placeholder-icon="search"
					border-color="#FFFFFF"
					text-color="#FFFFFF"
					placeholder-color="#FFFFFF"
					class="search-class tn-m-sm tn-text-bold"
					search-button-bg-color="#6bb7ec"
					shape="round"
					/>
				
			</view>

		</tn-sticky>
		</template>
		<hr/>
		
		<view class="cards-class tn-mb-sm">
			<view class="tn-ml-sm tn-mr-sm tn-shadow-md tn-flex card-class" v-for="(item,index) in goodsData">
				<view class="tn-w-1-3">
					<image :src="item.imgurl" class="image-class" @tap="handleImageTap(item.imgurl)" mode="aspectFit" @error="imgerror(index)"></image>
				</view>
				<view class="tn-w-2-3 tn-p-xs  tn-ml-sm">
					<view class="tn-text-bold tn-text">
						{{item.goodsname}}
					</view>
					<view class="tn-text-ellipsis-2 tn-text-xs">
						{{item.manufacturer}}
					</view>
					<view class="tn-text-xs">
						<!-- {{item.goodsspec}}({{item.wmsmeas}}/{{item.unit}}/{{item.wmsutil}}) -->
						{{item.specunitinfo}}
					</view>
					<view class="tn-text-xs">
						{{item.valdateinfo}}
					</view>
					<view class="tn-text-xs">
						{{item.stock}}
					</view>
					<view class="tn-text-xs">
						{{item.sumstock}}
					</view>
					<view class="tn-text-xs">
						{{item.salepriceinfo}}
					</view>
					<view class="tn-text-xs">
						{{item.retailpinfo}}
					</view>
					<view class="input-class tn-mt-xs">
						<tn-form-item label="数&nbsp;&nbsp;&nbsp;量" class="tn-text-bold tn-text-sm">
							<tn-input v-model="item.num" placeholder="请输入数量" size="sm" border-color="#000000" type="number"/>
						</tn-form-item>
						<tn-form-item label="价&nbsp;&nbsp;&nbsp;格" class="tn-text-bold tn-text" v-if="item.oldtaxprice==null">
							<tn-input v-model="item.taxprice" :placeholder="item.lastsalepriceinfo" size="sm" border-color="#000000" :placeholder-style="placeholderStyle" type="text" inputmode="decimal"  min="0" max="999999" step="0.01" pattern="\d+(\.\d{1,2})?"/>
						</tn-form-item>
					</view>
					 
					<tn-icon name="add-fill" color="#6caff6" size="60" class="card-icon-class" @click="addShopping(item)" />
				</view>
			</view>
		</view>
		
		
		
		<template #bottom>
			<view class="bottom-class ">
				<view class="">
					<tn-button type="success" size="xl" >已添加品种数：{{planShopClientInfo.details.length}}</tn-button>
				</view>
				<view class="">
					<tn-button type="danger" size="xl" @click="toNavigate">去购物车</tn-button>
				</view>
			
			</view>
		</template>
		
	</z-paging>	
	<!-- </view> -->
</template>

<script setup>
	import { ref,reactive,onMounted} from "vue"
	import TnDropdown from 'tnuiv3p-tn-dropdown/index.vue'
	import { postCall  } from '@/api/index.js'
	import { createParams,pinToTop,isHeaderClass } from '@/utils/utils.js'
	import { EventBus } from '@/mitt/EventBus.js';
	import { toastMessage } from '@/utils/toast.js'
	const headerClass = ref('');
	const procName = "PROC_APP_DO_PLAN";
	const procNameShop = "PROC_APP_DO_SHOPPING"
	const page = ref(1);
	const pageCount = ref(20);
	let currentTabsIndex = ref(0)
	const paging = ref(null)
	let noneGoodsImageUrl = ref("");
	let pageInfo = {
		P_PAGE : 1 ,
		P_PAGESIZE : 10
	}
	
	const imgerror = (index)=>{
		if(goodsData.value.length>0){
			goodsData.value[index].imgurl = noneGoodsImageUrl.value;
		}
	}
	
	const queryList = (pageNo, pageSize) =>{
		pageInfo.P_PAGE = pageNo;
		pageInfo.P_PAGESIZE = pageSize;
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "GOODS";	
		params["P_CLIENTID"] = hz.businessid;
		params["P_CON"] = searchValue.value;
		postCall(Object.assign( Object.assign(params,createParams(pageInfo)),pageInfo)).then(res=>{
			if(res){
				if(res.code===200 || res.code===1000){
					paging.value.complete(res.data.DATASET);
				}
			}
			
		}).catch(res =>{
			paging.value.complete(false);
		})
	}
	
	const searchBtnClickEventPage = () =>{
		paging.value.reload();
	}	
	
	const hz = reactive({
		"businessid":"",
		"businesscode":"",
		"businessname":"请选择供应商"
	})
	let planShopClientInfo = reactive({
		details:[]
	})

	 onMounted(() => {
	    
		doGetSupp();
		// doGetGoods();
		EventBus.on('suppInfo', (objParam) => {
			Object.assign(hz,objParam);
			console.log(hz);
			// doGetGoods();
			// paging.value.reload();
			getShopInfo();
		});
		EventBus.on('planShopClientInfo', (objParam) => {
			getShopInfo();
		});
		getShopInfo();
		const httpUrl = uni.getStorageSync("HTTP");
		noneGoodsImageUrl.value  =  httpUrl+'/static/none.png';
		// Object.assign(planShopClientInfo,uni.getStorageSync("PLANSHOPCLIENTINFO"));
	});
	
	let doGetSupp = () =>{
		let supplyInfo = uni.getStorageSync("SUPPINFO");
		Object.assign(hz,supplyInfo);
	}
	
	
	let goodsData = ref([]);
	let doGetGoods = () =>{
		goodsData.length = 0;
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "GOODS";	
		params["P_CLIENTID"] = hz.businessid;
		postCall(Object.assign(params,createParams(pageInfo))).then(res=>{
			if(res){
				if(res.code===200){
					Object.assign(goodsData,res.data.DATASET);
				}
			}
			
		})
	}
	
	let selSupp = () =>{
		uni.navigateTo({
			url: '/pages/purplan/supp'
		})
	}
	const searchValue = ref("")
	const currentSwiperIndex = ref(1)
	const placeholderStyle = reactive({
		color:"#000000"
	})
	
	const searchInputEvent = () =>{
		
	}
	const searchBtnClickEvent = () =>{
		
	}
	const openDropdown = ref(false);
	
	const numValue = ref()
	const priceValue = ref()
	
	
	let handleImageTap=(val)=>{
		uni.previewImage({
			urls: [val], // 要预览的图片链接列表
			current: 0, // 当前显示图片的链接（必须是urls中的一个），索引从0开始
		});
	}
	const addShopping= (val)=>{
		let params = {};
		params["P_PROC_NAME"] = procNameShop;
		params["P_ACTION"] = "PLAN_ADD";
		params["P_SUPPLIERSID"] = hz.businessid;
		params["P_GOODSID"] = val.goodsid;
		params["P_TAXPRICE"] = val.taxprice;
		params["P_NUM"] = val.num;
		params["P_ADDRESSID"] = hz.addressid;
		params["P_RECEMANID"] = hz.recemanid;
		params["P_SALEDEPTID"] = val.saledeptid;
		params["P_INNERPRICE"] = val.innerprice;
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					getShopInfo().then(re=>{
						toastMessage("添加成功！");
					});
				}
			}
			
		})
	}
	let getShopInfo = async () =>{
		planShopClientInfo.details = [];
		let tempOrderData  = [];
		let convertOrderData = [];
		let params = {};
		params["P_PROC_NAME"] = procNameShop;
		params["P_ACTION"] = "PLAN_QUERY";
		params["P_SUPPLIERSID"] = hz.businessid;
		await postCall(params).then(res=>{
			if(res){
				if(res.code===200){
							   Object.assign(tempOrderData,res.data.DATASET);	   
							   // console.log(statusData);
							   const mergedData = tempOrderData.reduce((acc, cur) => {
							       const { billno,billcode, businessname,recemanname,address,recetelephone,businessid,subbranch,bankaccount,acctname, ...rest } = cur;
							       if (!acc[billcode]) {
							           acc[billcode] = { billno,billcode, businessname,recemanname,address,recetelephone,businessid,subbranch,bankaccount,acctname, details: [rest] };
							       } else {
							           acc[billcode].details.push(rest);
							       }
							       return acc;
							   }, {});
							   
							   const businessStats = {};
							   for (const key in mergedData) {
							       const business = mergedData[key];
							       const totalPrice = business.details.reduce((total, item) => total + item.sumtaxamount, 0);
										mergedData[key]["taxamount"] = totalPrice;
								   }
							    for (const key in mergedData) {
							   	    if (Object.hasOwnProperty.call(mergedData, key)) {
									   convertOrderData.push(mergedData[key]);
									}
							     }
								uni.setStorageSync("PLANSHOPCLIENTINFO",convertOrderData[0]) 
								Object.assign(planShopClientInfo,convertOrderData[0])
				}
			}
		   
		})
	}
	
	let toNavigate = async () =>{
		if(planShopClientInfo.details.length==0){
			toastMessage("请选择添加购物车的产品！");
		}else{
			await getShopInfo();
			uni.navigateTo({
				url: '/pages/purplan/shopdetails'
			})
			
		}
		
	}
</script>

<style scoped>
page{
	overflow-x: hidden;
}


.header-class-app{
	height: 20vh !important;
	flex-direction: column
 } 

.header-class-wechat{
	height: 17vh !important;
	flex-direction: column
}
.header-class{
	height: 20vh !important;
	flex-direction: column
}

.search-class{
	/* background-color: #ffffff; */
	
}
.icon-class{
	width: 15vw;
}

.dropdown-menu {
  position: relative;
  width: 30vw;
}
.dropdown-menu-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}	


.dropdown-content {
  width: 90vw;
  height: 500rpx;
  background-color: #FFFFFF;
}
.uni-scroll-view-content{
	width: 90vw !important;
}
.tn-dropdown__content{
	width: 90vw !important;
	background-color: #000000 !important;
}
.image-class{
	width: 100%;
	height: 100%;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.preview-image {
	max-width: 80%;
	max-height: 50%;
	object-fit: contain;
	position: absolute; 
}

.card-class{
	position: relative;
}
.card-icon-class{
	position: absolute;
	bottom: 30px; 
	right: 20px;
}
.input-class{
	width: 40vw;
}

.tn-form-item{
	margin-bottom: 0.2rem !important;
}
.cards-class{
	padding-bottom: 8.5vh;
}

.bottom-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background-color: #fff; /* 设置底部背景色 */
	padding: 10px; /* 设置内边距 */
	display: flex;
	justify-content: space-between;
	box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 设置底部阴影 */
	padding-bottom: calc(env(safe-area-inset-bottom) + 20px);
	height: 8vh;
}

.bottom-class{
	/* margin-top: 10px; */
	padding: 10px;
	height: 8vh;
	display: flex;
	justify-content: space-between;
	box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); 
	padding-bottom: calc(env(safe-area-inset-bottom) + 20px);
}

</style>
